import json
import logging
from appium.options.android import UiAutomator2Options
from appium import webdriver
from logging import handlers
from config import ANDROID_DESIRE_CAPS, URL, PATH


class Tools:
    driver = None
    des_caps = ANDROID_DESIRE_CAPS
    @classmethod
    def get_app_driver(cls):
        if cls.driver is None:
            option = UiAutomator2Options().load_capabilities(cls.des_caps)
         # 创建驱动对象
            cls.driver = webdriver.Remote(URL+"/wd/hub", options=option)
        return cls.driver
    @classmethod
    def quit_app_driver(cls):
        if cls.driver is not None:
            cls.driver.quit()
            cls.driver = None
class GetLog:
    # 日志器
    __log = None

    @classmethod
    def get_log(cls):
        if cls.__log is None:
            # 获取日志器
            cls.__log = logging.getLogger()
            # 设置入口级别
            cls.__log.setLevel(logging.INFO)
            # 获取处理器
            filename = PATH + "/log/" + "app-{}log"
            tf = logging.handlers.TimedRotatingFileHandler(filename=filename,
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=3,
                                                           encoding="utf-8")
            # 获取格式器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fm = logging.Formatter(fmt)
            # 将格式器添加到处理器
            tf.setFormatter(fm)
            # 将处理器添加到日志器
            cls.__log.addHandler(tf)
        # 返回日志器
        return cls.__log
def read_json(file_name):
    """
    读取JSON文件并转换为格式为 [(), (), ...] 的列表
    :param file_name: json文件名
    :return: 列表
    """
    data = []
    file_path = PATH + "/data/" + file_name
    with open(file_path, mode='r', encoding='utf-8') as f:
        # 读取JSON文件并解析为Python对象
        tmp = json.load(f)
        for i in tmp:
            a = tuple(i.values())
            data.append(a)
        # 返回列表
        return data







